package com.aggregate.pay.lianlianpay.support.client;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import com.aggregate.pay.lianlianpay.bean.NotifyData;
import com.aggregate.pay.lianlianpay.support.Client;
import com.aggregate.pay.lianlianpay.support.Factory;
import com.aggregate.pay.lianlianpay.support.Merch;
import com.aggregate.pay.lianlianpay.support.Tool;
import com.aggregate.pay.lianlianpay.support.utils.JSON;

/**
 * 代付回调处理
 * @author Moyq5
 * @date 2019年4月26日
 */
public class NotifyPay implements Client<HttpServletRequest, NotifyData> {
	public static final String CHARSET = "UTF-8";
	
	public NotifyPay(Merch merch) {}
	@Override
	public NotifyData execute(HttpServletRequest req) {
		log.debug("连连付代付回调 -> 请求地址：{}", req.getRequestURI());
		log.debug("连连付代付回调 -> 请求参数：{}", req.getQueryString());
		NotifyData data = new NotifyData();
		try {
			InputStream is = req.getInputStream();
			byte[] b = new byte[1024];
			int i;
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			while((i=is.read(b)) != -1) {
				os.write(b, 0, i);
			}
			is.close();
			os.close();
			String reqBody = os.toString(CHARSET);
			
			log.debug("连连付代付回调 -> 请求报文：{}", reqBody);
			
			data = JSON.toObject(reqBody, NotifyData.class);
			
			if (!Tool.verify(Tool.toQueryString(reqBody), data.getSign(), Factory.getConfig().publicKey())) {
				throw new Exception("连连付代付回调 -> 签名验证失败");
			}
		} catch (Exception e) {
			log.error("连连付代付回调 -> 处理失败", e);
			throw new RuntimeException(e);
		}
		return data;
	}
	
}
